import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { resetRouter } from '@/router'
import { constantRoutes } from '@/router'
//保存
const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}

//修改
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
  }
}

//操作
const actions = {
  async login(context, data) {
    console.log(data)
    const token = await login(data)
    context.commit('setToken', token)

  },
  loginOut(context) {
    context.commit('setUserInfo', {})
    context.commit('removeToken')
    //重置路由
    resetRouter()
  },
  async setUserInfo(context) {
    const result = await getUserInfo();
    console.log('用户信息--' + result)
    context.commit('setUserInfo', result)
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

